package com.yatb.trac.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.util.StringUtils;

public class CheckSessionFilter implements Filter {

	private List<String> excludeCheckForPages = new ArrayList<String>();

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		((HttpServletResponse)response).setHeader("Cache-Control","no-store, no-cache, must-revalidate"); //HTTP 1.1
		((HttpServletResponse)response).setHeader("Pragma","no-cache"); //HTTP 1.0
		((HttpServletResponse)response).setDateHeader ("Expires", 0); //prevents caching at the proxy server

		if (((HttpServletRequest) request).getSession(false) == null) {
			((HttpServletRequest) request).getSession(true);
			String uri = ((HttpServletRequest) request).getRequestURI();
			uri = uri.substring(uri.indexOf(((HttpServletRequest) request)
					.getContextPath())
					+ ((HttpServletRequest) request).getContextPath().length());
			if (!excludeCheckForPages.contains(uri)) {
				request.getRequestDispatcher("/login.do").forward(request,
						response);
				return;
			}
		}
		filterChain.doFilter(request, response);
	}

	public void init(FilterConfig config) throws ServletException {
		String exclude = config.getInitParameter("excludePages");
		StringTokenizer st = new StringTokenizer(exclude,",",false);
		while (st.hasMoreElements()) {
			String string = (String) st.nextElement();
			excludeCheckForPages.add(string);
		}
	}

}
